#pragma once
#include <iostream>
#include <functional>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/wait.h>
#include <pthread.h>
#include "Log.hpp"
#include "InetAddr.hpp"


using namespace log_ns;

enum 
{
    SOCKET_ERROR,
    BIND_ERROR,
    LISTEN_ERROR
};

const static uint16_t gport = 8888;
const static int gsockfd = -1;
const static int gblcklog = 8;

using command_service_t = std::function<void(int sockfd,InetAddr addr)>;

// 面向字节流
class TcpServer
{
public:
    TcpServer(command_service_t service,uint16_t port = gport)
        :_service(service), _port(port),_listensockfd(gsockfd),_isrunning(false)
    {}

    void InitServer()
    {
        // 1.创建socket
        _listensockfd = ::socket(AF_INET,SOCK_STREAM,0);
        if(_listensockfd < 0)
        {
            LOG(FATAL,"socket create eror\n");
            exit(SOCKET_ERROR);
        }
        LOG(INFO,"socket create success,sockfd: %d\n",_listensockfd); // 3

        struct sockaddr_in local;
        memset(&local,0,sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = INADDR_ANY;

        // 2.bind sockfd 和 socket addr
        if(::bind(_listensockfd,(struct sockaddr*)&local,sizeof(local)) < 0)
        {
            LOG(FATAL,"bind eror\n");
            exit(BIND_ERROR);
        }
        LOG(INFO,"bind success\n");

        // 3.因为tcp是面向连接的，tcp需要未来不短地获取连接
        // 老板模式，随时等待被连接
        if(::listen(_listensockfd,gblcklog) < 0)
        {
            LOG(FATAL,"listen eror\n");
            exit(LISTEN_ERROR);
        }
        LOG(INFO,"listen success\n");
    }
    // 内部类
    class ThreadData
    {
    public:
        int _sockfd;
        TcpServer* _self;
        InetAddr _addr;
    public:
        ThreadData(int sockfd,TcpServer* self,const InetAddr &addr)
            :_sockfd(sockfd),_self(self),_addr(addr)
        {}
    };
    void Loop()
    {
        _isrunning = true;
        while(_isrunning)
        {
            struct sockaddr_in client;
            socklen_t len = sizeof(client);
            // 1.获取新连接
            int sockfd = ::accept(_listensockfd,(struct sockaddr*)&client,&len);
            // 获取失败继续获取
            if(sockfd < 0)
            {
                LOG(WARNING,"sccept reeor\n");
                continue;
            }
            InetAddr addr(client);
            LOG(INFO,"get a new link,client info: %s,sockfd:%d\n",addr.AddrStr().c_str(),sockfd); // 4
            
            // 获取成功
            // version 2 -- 多线程版 -- 不能关闭fd了，也不需要 
            pthread_t tid;
            ThreadData *td = new ThreadData(sockfd, this,addr);
            pthread_create(&tid,nullptr,Execute,td); // 新线程分离
        }
        _isrunning = false;
    }
    // 无法调用类内成员 无法看到sockfd
    static void *Execute(void *args)
    {
        ThreadData *td = static_cast<ThreadData *>(args);
        pthread_detach(pthread_self()); // 分离新线程，无需主线程回收
        td->_self->_service(td->_sockfd,td->_addr); // 执行回调
        ::close(td->_sockfd);
        delete td;
        return nullptr;
    }
    // void Server(int sockfd,InetAddr addr)
    // {
    //     // 长服务
    //     while(true)
    //     {
    //         char inbuffer[1024]; // 当做字符串
    //         // 1.读文件
    //         ssize_t n = ::read(sockfd,inbuffer,sizeof(inbuffer) - 1);
    //         if(n > 0)
    //         {
    //             inbuffer[n] = 0;
    //             LOG(INFO,"get message from client [%s],message: %s\n",addr.AddrStr().c_str(),inbuffer);
    //             std::string echo_string = "[server echo]# ";
    //             echo_string += inbuffer;

    //             // 2.写文件
    //             write(sockfd,echo_string.c_str(),echo_string.size());
    //         }
    //         // 读到文件结尾
    //         else if(n == 0)
    //         {
    //             LOG(INFO,"client %s quit\n",addr.AddrStr().c_str());
    //             break;
    //         }
    //         else
    //         {
    //             LOG(ERROR,"read error\n",addr.AddrStr().c_str());
    //             break;
    //         }
    //     }
    // }
    ~TcpServer()
    {}
private:
    uint16_t _port;
    int _listensockfd;
    bool _isrunning;

    command_service_t _service;
};